package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponVo;
import com.atguigu.gulimall.order.entity.OmsOrderItemEntity;
import com.atguigu.gulimall.order.entity.OmsPaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OmsOrderItemService;
import com.atguigu.gulimall.order.service.OmsPaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sun.xml.internal.bind.v2.TODO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OmsOrderDao;
import com.atguigu.gulimall.order.entity.OmsOrderEntity;
import com.atguigu.gulimall.order.service.OmsOrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


import static com.atguigu.common.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;

@Slf4j
@Service("omsOrderService")
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderDao, OmsOrderEntity> implements OmsOrderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired 
     private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WmsFeignService wmsFeignService;;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OmsOrderItemService orderItemService;
    @Autowired
    private OmsPaymentInfoService paymentInfoService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal();
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OmsOrderEntity> page = this.page(
                new Query<OmsOrderEntity>().getPage(params),
                new QueryWrapper<OmsOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        //feign远程调用会丢失请求头信息
        //因此在feign调用前配置拦截器
        //如果是异步任务request需要共享主线程的request中的信息,因此每个线程都要设置一下请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有收获地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> getCarItems = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车所有选中的购物项
            List<OrderItemVo> items = cartFeignService.currentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            //批量查询每个商品的库存信息
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {});
            if(CollectionUtils.isNotEmpty(data)){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);
        //查询用户积分
        Integer integration = memberResponVo.getIntegration();
        confirmVo.setIntegration(integration);
        CompletableFuture.allOf(getCarItems, getAddressFuture).get();
        //其他数据自动计算
        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX+memberResponVo.getId(), token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        return confirmVo;
    }

    /**
     * 用户下单
     * @param vo
     * @return
     */
    //REQUIRED REQUIRES_NEW
    //REPEATABLE_READ 可重复都mysql默认
    //@GlobalTransactional
    @Transactional  //本地事务,在分布式系统控制自己的回滚,控制不了其他的服务回滚
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);
        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        //创建订单,验证令牌,验证价格,锁库存

        String orderToken = vo.getOrderToken();
        //1、验证令牌是否合法【令牌的对比和删除必须保证原子性】
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //通过lure脚本原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(USER_ORDER_TOKEN_PREFIX+memberResponVo.getId()),orderToken);
        if(result==0L){
            response.setCode(1);
            return response;
        }
         //创建订单订单项等相关信息
        OrderCreateTo order = createOrder();
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        if(!(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01)){
            //金额对比失败
            response.setCode(2);
            return response;
        }
        //保存订单
        saveOrder(order);
        //锁定库存,只要异常回滚订单数据
        //订单号,所有订单项 skuId skuNumber,skuNo
        WareSkuLockVo lockVo = new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
            OrderItemVo itemVo = new OrderItemVo();
            itemVo.setSkuId(item.getSkuId());
            itemVo.setCount(item.getSkuQuantity());
            itemVo.setTitle(item.getSkuName());
            return itemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(collect);
        //TODO 远程锁库存
        R r = wmsFeignService.orderLockStock(lockVo);
        if(r.getCode()==0){
            
            response.setOrder(order.getOrder());
            //int i = 10/0;
            //TODO 订单创建成功发送消息给MQ
            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
            //为了保证高并发,库存服务自己回滚
            return response;
        }else{
            String msg = (String) r.get("msg");
            throw new NoStockException(msg);
            //response.setCode(3);
            //return response;
        }

    }

    @Override
    public OmsOrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OmsOrderEntity>().eq("order_sn",orderSn));

    }

    @Override
    public void closeOrder(OmsOrderItemEntity order) {
        //关闭订单之前查询当前订单的最新状态
        OmsOrderEntity orderEntity = this.getById(order.getId());
        if(orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OmsOrderEntity update = new OmsOrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //订单取消成功
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            try {
                //TODO 保证消息百分之百发送出去,每一个消息做日志记录(给数据库保存一个详细记录)
                //TODO 定期扫描数据库将数据失败的消息
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (Exception e) {
                //TODO 将没发送成功的消息进行重试发送
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取当前订单支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OmsOrderEntity order = this.getOrderByOrderSn(orderSn);
        //有小说点向上取值
        BigDecimal decimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(decimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        List<OmsOrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OmsOrderItemEntity>().eq("order_sn", orderSn));
        OmsOrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        IPage<OmsOrderEntity> page = this.page(
                new Query<OmsOrderEntity>().getPage(params),
                new QueryWrapper<OmsOrderEntity>().eq("member_id",memberResponVo.getId()).orderByDesc("id")
        );
        List<OmsOrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OmsOrderItemEntity> entities = orderItemService.list(new QueryWrapper<OmsOrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(entities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);
        return new PageUtils(page);

        
    }

    /**
     * 处理老师支付宝结果
     * @param vo
     * @return
     */
    @Override
    public String handlerPayResult(PayAsyncVo vo) {
       //保存交易流水
        OmsPaymentInfoEntity infoEntity = new OmsPaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功
            String orderSn = vo.getOut_trade_no();
            this.baseMapper.updateOrderPayedStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo order) {
        //TODO  保存订单信息
        OmsOrderEntity orderEntity = new OmsOrderEntity();
        orderEntity.setOrderSn(order.getOrderSn());
        orderEntity.setMemberId(order.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = order.getSeckillPrice().multiply(new BigDecimal(order.getNum() + ""));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //TODO保存订单项
        OmsOrderItemEntity orderItemEntity = new OmsOrderItemEntity();
        orderItemEntity.setOrderSn(order.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(order.getNum());
        //TODO 获取当前spu详细信息
        orderItemService.save(orderItemEntity);

    }


    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OmsOrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OmsOrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
        //适应seata修改代码seata不能批量插入
        //for (OmsOrderItemEntity orderItem : orderItems) {
        //    orderItemService.save(orderItem);
        //}


    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OmsOrderEntity orderEntity = buildOrder(orderSn);
        //获取所有的订单项
        List<OmsOrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //计算价格相关
        computerPrice(orderEntity, itemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(itemEntities);
        return orderCreateTo;
    }

    private void computerPrice(OmsOrderEntity orderEntity, List<OmsOrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integrationAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额叠加每一个订单项的总额信息
        for (OmsOrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integrationAmount = integrationAmount.add(entity.getIntegrationAmount());
            promotionAmount = promotionAmount.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
            

        }
        //订单相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        orderEntity.setCouponAmount(coupon);
        //设置积分成长值
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//0:未删除
        
        
    }

    private OmsOrderEntity buildOrder(String orderSn) {
        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        OmsOrderEntity entity = new OmsOrderEntity();
        //设置订单号
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberResponVo.getId());
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData("data",new TypeReference<FareVo>(){});
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     * @return
     */
    private List<OmsOrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定购物价格
        //2.获取当前所有的订单项
        List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
        if(CollectionUtils.isNotEmpty(orderItemVos)){
            List<OmsOrderItemEntity> itemEntities = orderItemVos.stream().map(item -> {
                OmsOrderItemEntity itemEntity =  buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建指定订单项  
     * @param item
     * @return
     */
    private OmsOrderItemEntity buildOrderItem(OrderItemVo item) {
        //订单信息  
        //商品spu信息
        Long skuId = item.getSkuId();

        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {});
        OmsOrderItemEntity itemEntity = new OmsOrderItemEntity();
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //商品sku信息
        itemEntity.setSkuId(item.getSkuId());
        itemEntity.setSkuName(item.getTitle());
        itemEntity.setSpuPic(item.getImage());
        itemEntity.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(item.getCount());

        //优惠信息不做
        //积分信息
        itemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal orgin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orgin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        
        return itemEntity ;
    }
   
}